<template>
  <div>
    <el-drawer
      v-model="dialogVisible"
      :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
      width="600px"
      @close="reset"
    >
      <div class="scene-dialog">
        <p>基本信息</p>
        <el-form 
          ref="articleFormRef"
          :model="formItem" 
          :rules="rules"
          label-width="100"
          label-position="top"
          :disabled="!isDisabled"
        >
          <el-form-item label="MQTT协议名称" prop="mqttProtocolName">
            <el-select 
              v-model="formItem.mqttProtocolName" 
              placeholder="请选择MQTT协议"
              @change="handleMqttProtocolChange"
            >
              <el-option 
                v-for="item in mqttProtocolOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value" 
              />
            </el-select>
          </el-form-item>  

          <el-form-item label="网关名称" prop="gatewayName">
            <el-input v-model="formItem.gatewayName" />
          </el-form-item>

          <el-form-item label="所属组织" prop="orgId">
            <org-tree-select v-model="formItem.orgId" />
          </el-form-item>

          <el-form-item label="供应商产品系列编号" prop="deviceType">
            <el-input v-model="formItem.deviceType" />
          </el-form-item> 
        
          <el-form-item label="SN" prop="snCode">
            <el-input v-model="formItem.snCode" />
          </el-form-item>

          <el-form-item label="心跳周期" prop="heartCycle">
            <el-input-number 
              v-model="formItem.heartCycle"
              :min="1" 
              :precision="0"
            />
          </el-form-item>

          <el-form-item label="网关型号" prop="gatewayType">
            <el-input v-model="formItem.gatewayType" />
          </el-form-item>

          <el-form-item label="MAC" prop="macCode">
            <el-input v-model="formItem.macCode" />
          </el-form-item>

          <el-form-item label="网关地址" prop="gatewayAddress">
            <el-input v-model="formItem.gatewayAddress" />
          </el-form-item>

          <el-form-item label="设备描述" prop="gatewayDes">
            <el-input v-model="formItem.gatewayDes" />
          </el-form-item>

        </el-form>
      </div>
        
      <template #footer v-if="isDisabled">
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus==='create'?createData():updateData()"
          >确 定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { addGateway, editGateway } from '@/api/collect'
import { validate } from '@/utils/validate'
import OrgTreeSelect from '@/components/OrgTreeSelect/index.vue'

const isDisabled = ref(true)
const mqttProtocolOptions = [
  { label: '盛为MQTT协议', value: 0 },
  { label: '正泰MQTT协议', value: 1 },
]

const formItem = reactive({
  id: null as number | null,
  gatewayName: '',
  orgId: null,
  mqttProtocolName: '',
  deviceType: '',
  snCode: '',
  macCode: '',
  gatewayAddress: '',
  gatewayDes: '',
  gatewayType: '',
  heartCycle: 3,
  latitude: null as number | null,
  longitude: null as number | null
})

// 正泰MQTT协议时条件验证
const validateDeviceType = (rule: any, value: any, callback: any) => {
  if (formItem.mqttProtocolName === 1) {
    if (!value || (typeof value === 'string' && value.trim() === '')) {
      callback(new Error('当选择正泰MQTT协议时，供应商产品系列编号为必填'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const rules = reactive({
  mqttProtocolName: [{ required: true, message: '请选择MQTT协议名称', trigger: 'change' }],
  gatewayName: [{ required: true, message: '请输入网关名称', trigger: 'blur' }],
  orgId: [{ required: true, message: '请选择组织', trigger: 'change' }],
  deviceType: [{ validator: validateDeviceType, trigger: ['blur', 'change'] }],
  snCode: [{ required: true, message: '请输入SN', trigger: 'blur' }],
  macCode: [{ required: true, message: '请输入MAC', trigger: 'blur' }],
  heartCycle: [{ required: true, message: '请输入心跳周期', trigger: 'blur' }],
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const reset = () => {
  if (!articleFormRef) return
  articleFormRef.value.resetFields()
  Object.assign(formItem, {
    id: null,
    gatewayName: '',
    orgId: null,
    mqttProtocolName: 0,
    deviceType: '',
    snCode: '',
    macCode: '',
    gatewayAddress: '',
    gatewayDes: '',
    gatewayType: '',
    heartCycle: 3,
    latitude: null,
    longitude: null
  })
  isDisabled.value = false
}

const articleFormRef = ref(null)

const handleMqttProtocolChange = () => {
  // 当MQTT协议名称改变时，重新验证供应商产品系列编号字段
  articleFormRef.value?.validateField('deviceType')
}

const emit = defineEmits(['listChange'])

const createData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    // 创建时排除id字段
    const { id, ...createData } = formItem
    addGateway(createData)
      .then(() => {
        emit('listChange')
        dialogVisible.value = false
        ElMessage.success('创建成功！')
      })
      .catch(() => {
        ElMessage.error('创建失败！')
      })
  }
}

const updateData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    // 更新时必须包含id字段
    if (!formItem.id) {
      ElMessage.error('更新失败：缺少ID信息')
      return
    }
    editGateway(formItem)
      .then(() => {
        emit('listChange')
        dialogVisible.value = false
        ElMessage.success('更新成功！')
      })
      .catch(() => {
        ElMessage.error('更新失败！')
      })
  }
}

defineExpose({ dialogVisible, formItem, isDisabled, dialogStatus, reset })
</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 20px;
}
.scene-dialog {
  margin-top: 10px;
  p {
    margin-top: 0;
  }
}
</style>
